import React from 'react';
import { Card, Form, Input, DatePicker, Select, Button, Space, Table, Tag, Modal, message } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, ReloadOutlined } from '@ant-design/icons';

const { RangePicker } = DatePicker;
const { Option } = Select;

// 模拟字典
const LEVEL_LIST = [
  { value: '0', label: '基础' },
  { value: '1', label: '标准' },
  { value: '2', label: '高级' },
];
const RECEIVE_TYPE_LIST = [
  { value: '1', label: '邮箱' },
  { value: '2', label: '短信' },
  { value: '3', label: '线下' },
];

export default function ICard() {
  const [form] = Form.useForm();
  const [editForm] = Form.useForm();
  const [loading, setLoading] = React.useState(false);
  const [dialogOpen, setDialogOpen] = React.useState(false);
  const [current, setCurrent] = React.useState(null);
  const [list, setList] = React.useState(() => {
    const saved = localStorage.getItem('icard-list');
    if (saved) return JSON.parse(saved);
    // 初始模拟数据
    return Array.from({ length: 12 }).map((_, i) => ({
      id: i + 1,
      userName: `user_${i + 1}`,
      cardNo: `IC${String(100000 + i)}`,
      cardName: `IC卡-${i + 1}`,
      level: String(i % LEVEL_LIST.length),
      useMode: String(i % LEVEL_LIST.length),
      receiveType: String((i % RECEIVE_TYPE_LIST.length) + 1),
      availableNum: 1 + (i % 3),
      last: 1 + (i % 3),
      used: i % 2,
      amount: (10 + i).toFixed(2),
      notes: '示例数据',
      startTime: new Date(Date.now() - i * 86400000).toISOString(),
      endDate: new Date(Date.now() + (i % 5) * 86400000).toISOString(),
      createTime: new Date(Date.now() - i * 86400000).toLocaleString(),
    }));
  });
  const [filtered, setFiltered] = React.useState(list);

  React.useEffect(() => {
    localStorage.setItem('icard-list', JSON.stringify(list));
    setFiltered(list);
  }, [list]);

  const labelOf = (arr, v) => arr.find((x) => x.value === String(v))?.label || v;

  const handleSearch = () => {
    const { userName, cardNo, cardName, dateRange } = form.getFieldsValue();
    const res = list.filter((x) => {
      const m1 = userName ? x.userName.toLowerCase().includes(userName.toLowerCase()) : true;
      const m2 = cardNo ? x.cardNo.toLowerCase().includes(cardNo.toLowerCase()) : true;
      const m3 = cardName ? x.cardName.toLowerCase().includes(cardName.toLowerCase()) : true;
      let m4 = true;
      if (dateRange && dateRange.length === 2) {
        const [start, end] = dateRange;
        const st = start.startOf('day').valueOf();
        const ed = end.endOf('day').valueOf();
        const ct = new Date(x.createTime).valueOf();
        m4 = ct >= st && ct <= ed;
      }
      return m1 && m2 && m3 && m4;
    });
    setFiltered(res);
  };

  const onReset = () => {
    form.resetFields();
    setFiltered(list);
  };

  const openDialog = (record) => {
    setCurrent(record || null);
    setDialogOpen(true);
    if (record) {
      editForm.setFieldsValue({ ...record });
    } else {
      editForm.resetFields();
      editForm.setFieldsValue({ level: '0', receiveType: '1', availableNum: 1, last: 1, used: 0 });
    }
  };

  const saveICard = async () => {
    try {
      const values = await editForm.validateFields();
      setList((prev) => {
        if (!current) {
          const id = Date.now();
          return [{ id, createTime: new Date().toLocaleString(), ...values }, ...prev];
        }
        return prev.map((x) => (x.id === current.id ? { ...x, ...values } : x));
      });
      setDialogOpen(false);
      message.success('IC卡已保存（本地模拟）');
    } catch (e) {}
  };

  const resetICard = (record) => {
    Modal.confirm({
      title: '重置确认',
      content: `确定重置 IC卡 ${record.cardNo} 的使用数据吗？`,
      onOk: () => {
        setList((prev) => prev.map((x) => (x.id === record.id ? { ...x, used: 0, last: x.availableNum } : x)));
        message.success('已重置（本地模拟）');
      },
    });
  };

  const delICard = (record) => {
    Modal.confirm({
      title: '删除确认',
      content: `确定删除 IC卡 ${record.cardNo} 吗？`,
      onOk: () => {
        setList((prev) => prev.filter((x) => x.id !== record.id));
        message.success('已删除该 IC卡');
      },
    });
  };

  const columns = [
    { title: '用户名', dataIndex: 'userName', key: 'userName', width: 150, align: 'center' },
    { title: '卡号', dataIndex: 'cardNo', key: 'cardNo', width: 200, align: 'center' },
    { title: '卡名称', dataIndex: 'cardName', key: 'cardName', width: 200, align: 'center' },
    { title: '等级', dataIndex: 'level', key: 'level', width: 130, align: 'center', render: (v) => <Tag color="blue">{labelOf(LEVEL_LIST, v)}</Tag> },
    { title: '使用模式', dataIndex: 'useMode', key: 'useMode', width: 130, align: 'center', render: (v) => <Tag>{labelOf(LEVEL_LIST, v)}</Tag> },
    { title: '领取方式', dataIndex: 'receiveType', key: 'receiveType', width: 130, align: 'center', render: (v) => <Tag color="purple">{labelOf(RECEIVE_TYPE_LIST, v)}</Tag> },
    { title: '可用数量', dataIndex: 'availableNum', key: 'availableNum', width: 130, align: 'center' },
    { title: '剩余', dataIndex: 'last', key: 'last', width: 150, align: 'center' },
    { title: '已用', dataIndex: 'used', key: 'used', width: 100, align: 'center' },
    { title: '金额', dataIndex: 'amount', key: 'amount', width: 100, align: 'center' },
    { title: '备注', dataIndex: 'notes', key: 'notes', align: 'center' },
    { title: '创建时间', dataIndex: 'createTime', key: 'createTime', width: 160, align: 'center' },
    { title: '操作', key: 'actions', fixed: 'right', width: 220, align: 'center', render: (_, record) => (
      <Space size="small">
        <Button size="small" icon={<EditOutlined />} onClick={() => openDialog(record)}>编辑</Button>
        <Button size="small" type="primary" icon={<ReloadOutlined />} onClick={() => resetICard(record)}>重置</Button>
        <Button size="small" danger icon={<DeleteOutlined />} onClick={() => delICard(record)}>删除</Button>
      </Space>
    ) },
  ];

  return (
    <div className="icard" style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <Card title="IC卡管理" variant="outlined">
        <Form form={form} layout="inline" onFinish={handleSearch} style={{ rowGap: 12 }}>
          <Form.Item label="用户名" name="userName"><Input allowClear placeholder="请输入用户名" style={{ width: 180 }} /></Form.Item>
          <Form.Item label="卡号" name="cardNo"><Input allowClear placeholder="请输入卡号" style={{ width: 180 }} /></Form.Item>
          <Form.Item label="卡名称" name="cardName"><Input allowClear placeholder="请输入名称" style={{ width: 180 }} /></Form.Item>
          <Form.Item label="时间范围" name="dateRange"><RangePicker /></Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">查询</Button>
              <Button onClick={onReset}>重置</Button>
              <Button type="primary" icon={<PlusOutlined />} onClick={() => openDialog(null)}>新增</Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>

      <Card title={`IC卡列表（共 ${filtered.length} 条）`} variant="outlined">
        <Table
          rowKey="id"
          dataSource={filtered}
          loading={loading}
          columns={columns}
          pagination={{ pageSize: 10 }}
          scroll={{ x: 1400 }}
        />
      </Card>

      <Modal open={dialogOpen} title={current ? '编辑 IC卡' : '新增 IC卡'} okText="保存" cancelText="取消" onOk={saveICard} onCancel={() => setDialogOpen(false)}>
        <Form form={editForm} layout="vertical">
          <Form.Item label="用户名" name="userName" rules={[{ required: true, message: '请输入用户名' }]}>
            <Input placeholder="例如：user_001" />
          </Form.Item>
          <Form.Item label="卡号" name="cardNo" rules={[{ required: true, message: '请输入卡号' }]}>
            <Input placeholder="例如：IC100001" />
          </Form.Item>
          <Form.Item label="卡名称" name="cardName" rules={[{ required: true, message: '请输入卡名称' }]}>
            <Input placeholder="例如：消费卡-基础版" />
          </Form.Item>
          <Form.Item label="等级" name="level" rules={[{ required: true, message: '请选择等级' }]}>
            <Select>
              {LEVEL_LIST.map((x) => <Option key={x.value} value={x.value}>{x.label}</Option>)}
            </Select>
          </Form.Item>
          <Form.Item label="使用模式" name="useMode" rules={[{ required: true, message: '请选择使用模式' }]}>
            <Select>
              {LEVEL_LIST.map((x) => <Option key={x.value} value={x.value}>{x.label}</Option>)}
            </Select>
          </Form.Item>
          <Form.Item label="领取方式" name="receiveType" rules={[{ required: true, message: '请选择领取方式' }]}>
            <Select>
              {RECEIVE_TYPE_LIST.map((x) => <Option key={x.value} value={x.value}>{x.label}</Option>)}
            </Select>
          </Form.Item>
          <Form.Item label="可用数量" name="availableNum" rules={[{ required: true, message: '请输入数量' }]}>
            <Input type="number" min={0} />
          </Form.Item>
          <Form.Item label="剩余" name="last" rules={[{ required: true, message: '请输入剩余' }]}>
            <Input type="number" min={0} />
          </Form.Item>
          <Form.Item label="已用" name="used" rules={[{ required: true, message: '请输入已用' }]}>
            <Input type="number" min={0} />
          </Form.Item>
          <Form.Item label="金额" name="amount">
            <Input placeholder="例如：20.00" />
          </Form.Item>
          <Form.Item label="备注" name="notes">
            <Input.TextArea rows={3} placeholder="备注信息" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}